#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
import cv2 as cv
import cv2
import threading
#from _pylief import NONE


drawing = False  # true if mouse is pressed
ix, iy = -1, -1
marking=True#正在标记,不读新图
list_points=[]
class RTSCapture(cv2.VideoCapture):
    """Real Time Streaming Capture.
    这个类必须使用 RTSCapture.create 方法创建，请不要直接实例化
    """

    _cur_frame = None
    _reading = False
    schemes = ["rtsp://", "rtmp://"] #用于识别实时流

    @staticmethod
    def create(url, *schemes):
        """实例化&初始化
        rtscap = RTSCapture.create("rtsp://example.com/live/1")
        or
        rtscap = RTSCapture.create("http://example.com/live/1.m3u8", "http://")
        """
        rtscap = RTSCapture(url)
        rtscap.frame_receiver = threading.Thread(target=rtscap.recv_frame, daemon=True)
        rtscap.schemes.extend(schemes)
        if isinstance(url, str) and url.startswith(tuple(rtscap.schemes)):
            rtscap._reading = True
        elif isinstance(url, int):
            # 这里可能是本机设备
            pass

        return rtscap

    def isStarted(self):
        """替代 VideoCapture.isOpened() """
        ok = self.isOpened()
        if ok and self._reading:
            ok = self.frame_receiver.is_alive()
        return ok

    def recv_frame(self):
        """子线程读取最新视频帧方法"""
        while self._reading and self.isOpened():
            ok, frame = self.read()
            if not ok: break
            self._cur_frame = frame
        self._reading = False

    def read2(self):
        """读取最新视频帧
        返回结果格式与 VideoCapture.read() 一样
        """
        frame = self._cur_frame
        self._cur_frame = None
        return frame is not None, frame

    def start_read(self):
        """启动子线程读取视频帧"""
        self.frame_receiver.start()
        self.read_latest_frame = self.read2 if self._reading else self.read

    def stop_read(self):
        """退出子线程方法"""
        self._reading = False
        if self.frame_receiver.is_alive(): self.frame_receiver.join()

img_rgb=None
img_therm=None
img_merge = np.zeros((200,400, 3), np.uint8)


#src1="rtsp://admin:qd123456@10.39.245.253/h265/ch1/main/av_stream"
#src2="rtsp://admin:qd123456@10.39.245.253/h265/ch2/main/av_stream"
src1="rtsp://admin:qd123123@10.39.245.249/h265/ch1/main/av_stream"
src2="rtsp://admin:qd123123@10.39.245.249/h265/ch2/main/av_stream"

rtscap1 = RTSCapture.create(src1)
rtscap1.start_read() #启动子线程并改变 read_latest_frame 的指向
rtscap2 = RTSCapture.create(src2)
rtscap2.start_read() #启动子线程并改变 read_latest_frame 的指向

cv.namedWindow('RGB')
cv.namedWindow('Therm')

img = np.zeros((400,400, 3), np.uint8)
sum=0
missd=0
while rtscap1.isStarted() and rtscap2.isStarted():
    #ok1, frame1 = vc.read()
    ok1, img_rgb = rtscap1.read_latest_frame() #read_latest_frame() 替代 read()
    ok2, img_therm = rtscap2.read_latest_frame()
    sum+=1
    
    if not(ok1): 
        pass
    else:
        cv.imshow('RGB', img_rgb)    
    if not(ok2):    
        pass
    else:
        w0,h0=img_therm.shape[1],img_therm.shape[0]
              
        xc=int(w0/2)
        yc=int(h0/2)
        img_therm_gray=cv2.cvtColor(img_therm,cv2.COLOR_BGR2GRAY)
        img_cut=img_therm_gray[yc-5:yc+5,xc-5:xc+5]
        cv.circle(img_therm, (xc,yc), 5, (0, 0, 255),1)
        wc,hc=img_cut.shape[1],img_cut.shape[0]
        num=wc*hc    
        sum=np.sum(img_cut)
        value=int(sum/num)
        cv2.putText(img_therm, str(value),(xc,yc-20), cv.FONT_HERSHEY_SIMPLEX, 2, (0,255,0),1)
        cv.imshow('Therm', img_therm)
        
    k = cv.waitKey(1) & 0xFF
    if k == 27:
        break    
cv.destroyAllWindows()
